package com.heima.user.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto dto) {
        if (StrUtil.hasEmpty(dto.getPhone(), dto.getPassword())) {
            //游客登录
            return ResponseResult.okResult(MapUtil.<String, Object>builder()
                    .put("token", AppJwtUtil.getToken(0L))
                    .build());
        }
        //正常用户登录 13678900201  13678900202
        LambdaQueryWrapper<ApUser> queryWrapper = Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone());
        ApUser apUser = super.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(apUser)) {
            //用户不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "此手机号的用户不存在");
        }

        //校验密码
        // String salt = apUser.getSalt();
        // String md5Password = DigestUtil.md5Hex(dto.getPassword() + salt);
        if (!BCrypt.checkpw(dto.getPassword(), apUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //密码正确，生成token
        String token = AppJwtUtil.getToken(Convert.toLong(apUser.getId()));
        //删除隐私数据
        apUser.setSalt(null);
        apUser.setPassword(null);

        return ResponseResult.okResult(MapUtil.<String, Object>builder()
                .put("token", token)
                .put("user", apUser)
                .build());
    }
}
